package leetcode;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 描述:三数之和(双指针)
 * 1.先排序
 * 2.指定一个数作为基数
 * 3.双指针不断靠拢，判断是否=0
 * 4.去重
 *
 * @author Madison You
 * @created 10:21
 */
public class Mid_15_ThreeSum {

    public static void main(String[] args) {
        int[] ints = {-1, 0, 1, 2, -1, -4};
        List<List<Integer>> lists = threeSum(ints);
    }

    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > 0) {
                return list;
            }
            /*如果基数相同的话，则必定会出现相同的*/
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                if (nums[i] + nums[left] + nums[right] > 0) {
                    right--;
                } else if ( nums[i] + nums[left] + nums[right] < 0) {
                    left++;
                } else {
                    List<Integer> integers = new ArrayList<>();
                    integers.add(nums[i]);
                    integers.add(nums[left]);
                    integers.add(nums[right]);
                    list.add(integers);
                    while (left < right && nums[right] == nums[right - 1]) right--;
                    while (left < right && nums[left] == nums[left + 1]) left++;
                    right--;
                    left++;
                }

            }
        }
        return list;
    }

}
